package ink.sunflowerk.handler;


import ink.sunflowerk.entity.ResponseVO;
import ink.sunflowerk.entity.User;
import ink.sunflowerk.exception.UserLoginException;
import ink.sunflowerk.service.UserService;
import ink.sunflowerk.utils.CheckImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserAction {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login.action", method = RequestMethod.GET)
    public ResponseVO<User> loginMethod(String uname, String upwd, String uyzm, HttpServletRequest request) {
        String yzmSession = (String) request.getSession().getAttribute("yzmSession");
        if (!yzmSession.equals(uyzm)) {
            throw new UserLoginException("验证码错误！");
        }
        User user = userService.loginMethod(uname, upwd);
        request.getSession().setAttribute("user", user);
        return new ResponseVO<User>(200, "登录成功！", user);
    }

    @RequestMapping(value = "/yzmImg.action", method = RequestMethod.GET)
    public void yzmImgMethod(HttpServletResponse resp, HttpServletRequest request) {
        try {
            CheckImage.getYzm(resp, request);
        } catch (Exception e) {
            throw new UserLoginException("获取验证码失败！");
        }
    }

    @RequestMapping(value = "/logout.action", method = RequestMethod.GET)
    public ResponseVO<String> logoutMethod(HttpServletRequest request) {
        request.getSession().invalidate();
        return new ResponseVO<String>(200, "登出成功！", null);
    }

    @RequestMapping(value = "/update.action", method = RequestMethod.PUT)
    public ResponseVO<String> updateMethod(@RequestBody User user, HttpServletRequest request) {
        userService.updateMethod(user);
        request.getSession().invalidate();
        return new ResponseVO<String>(200, "修改成功！", null);
    }
}
